<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-button size="default" type="primary" @click="handleAdd">新增</el-button>
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        border
        class="mt-3"
        stripe
        style="width: 100%"
        tooltip-effect="dark"
      >
        <!-- <el-table-column :index="indexMethod" label="序号" prop="碎片id" type="index" width="120px"></el-table-column> -->
        <el-table-column label="碎片ID" prop="id"></el-table-column>
        <el-table-column label="碎片名称" prop="name"></el-table-column>
        <el-table-column label="ICON" prop="icon">
          <template slot-scope="scope">
            <el-popover max-width="220" placement="right" trigger="hover">
              <img :src="scope.row.icon" alt="" style="max-width: 200px;max-height: 200px">
              <img slot="reference" :src="scope.row.icon" alt="" style="width: 50px;">
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="描述" prop="desc" show-overflow-tooltip width="300px">
          <template slot-scope="{row}">
            <p class="overflow-tooltip">{{ row.desc }}</p>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updated_at"></el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleEdit(scope.row)"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              class="color-red"
              @click="handleSDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <cus-pagination
        v-show="total > 0"
        :limit.sync="listQuery.perPage"
        :page.sync="listQuery.page"
        :total="total"
        @pagination="getTableData"
      />
    </el-card>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      @close="closeDialog"
    >
      <el-form ref="form" :inline="false" :model="formData" :rules="rules" label-width="120px" size="normal">
        <el-form-item label="碎片名称" prop="name">
          <el-input
            type="text"
            v-model="formData.name"
            placeholder="请输入碎片名称"
            :maxlength="8"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="碎片图案" prop="icon">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="beforeAvatarUpload"
            :file-list="fileList"
            :http-request="customizeUpload"
            :limit="1"
            :on-remove="handlePictureRemove"
            :on-success="handlePictureSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button v-if="!formData.icon" slot="trigger" size="small" type="primary">上传碎片图案</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="碎片描述" prop="desc">
          <el-input
            type="textarea"
            rows="5"
            v-model="formData.desc"
            placeholder="请输入碎片描述"
            resize="none"
            :maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <span slot="footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleOnSubmit">确定</el-button>
            </span>
    </el-dialog>

  </div>
</template>

<script>
import { chipList, chipEdit, chipAdd, chipDel } from '@/api/sunGame/sunGame'

export default {
  name: 'shardList',
  components: {},
  data() {
    return {
      dialogVisible: false,
      dialogVisible2: false,
      formData: {
        desc: undefined,
        icon: undefined,
        name: undefined,
        id: undefined
      },
      rules: {
        name: [{ required: true, message: '请输入碎片名称', trigger: 'blur' }],
        icon: [{ required: true, message: '请上传碎片图案', trigger: 'blur' }]
      },
      loading: false,
      tableData: [],
      listQuery: {
        page: 1,
        perPage: 20
      },
      total: 1,
      options: [
        {
          value: 1,
          label: '123'
        }
      ],
      fileList: [],
      dialogTitle: undefined
    }
  },
  created() {
    this.getTableData()
  },
  methods: {
    indexMethod(index) {
      return this.total - (this.listQuery.page - 1) * this.listQuery.perPage - index
    },
    // 网络请求
    /**
     * getTableData
     * @desc 获取表格数据
     */
    async getTableData() {
      this.loading = true
      for (let key in this.listQuery) {
        this.listQuery[key] = !this.listQuery[key] ? undefined : this.listQuery[key]
      }
      const { data, code } = await chipList(this.listQuery)
      if (code === 200) {

        this.tableData = data.list
        this.total = data.meta.total
      }
      this.loading = false

    },
    closeDialog() {
      if (this.$refs['form']) {
        this.$refs['form'].clearValidate() // 清除整个表单的校验
        this.$refs['form'].resetFields() // 清除整个表单的校验
      }
      this.fileList = []
      this.formData = {
        title: undefined,
        value: undefined,
        icon: undefined,
        sort: undefined,
        id: undefined
      }
    },

    handleOnSubmit() {

      this.$refs['form'].validate(valid => {
        if (valid) {

          for (let key in this.formData) {
            this.formData[key] = !this.formData[key] ? undefined : this.formData[key]
          }
          if (this.formData.id) {
            chipEdit(this.formData).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              }
              this.dialogVisible = false
              this.getTableData()
            })
          } else {
            chipAdd(this.formData).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              }
              this.dialogVisible = false
              this.getTableData()
            })
          }

        }
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑'
      this.formData = JSON.parse(JSON.stringify(row))
      if(row.icon) {

        this.fileList = [{
          url: row.icon
        }]
      }
      this.dialogVisible = true
    },
    handleSDelete(row) {
      this.$confirm('此操作不可恢复，是否继续删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        chipDel({
          id: row.id
        }).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
          }
          this.dialogVisible = false
          this.getTableData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleReset() {
      this.listQuery = {
        page: 1,
        perPage: 10
      }
      this.getTableData()
    },
    handleAdd() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp' || file.type === 'image/gif'
      // const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //     this.$message.error('请上传JPG/PNG格式的图片!')
      // }
      // if (!isLt2M) {
      //     this.$message.error('上传图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
    },
    handlePictureSuccess() {
      this.formData.icon = this.ossLastImgUrl
    },
    handlePictureRemove() {
      this.fileList = []
      this.formData.icon = undefined
    }
  }
}
</script>

<style lang="scss" scoped>
.infoBox {
  margin-top      : 15px;
  margin-bottom   : 15px;
  padding-bottom  : 15px;
  border          : 1px solid #999999;
  border-radius   : 10px;
  display         : flex;
  align-items     : baseline;
  justify-content : center;
  box-sizing      : border-box;
  padding-right   : 30px;

  .info_1 {
    display         : flex;
    justify-content : center;
    flex-direction  : column;
    width           : 100%;

    .info_2 {
      margin-top  : 15px;
      display     : flex;
      align-items : center;
      position    : relative;

      span {
        width      : 180px;
        text-align : right;
      }

      .tip {
        color     : red;
        font-size : 12px;
        position  : absolute;
        top       : 100%;
        left      : 120px;
      }
    }
  }
}

.item {
  width : 100px;
}

.formItemBox {
  display     : flex;
  align-items : center;
  flex-wrap   : wrap;

  width       : 100%;
  overflow    : hidden;
}

::v-deep {
  .formItemBox {
    .el-form-item {
      width : 50% !important;
    }
  }

}

.overflow-tooltip {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

</style>

